package xyz.zcq.springframework.beans.factory.support;

import xyz.zcq.springframework.beans.BeanException;
import xyz.zcq.springframework.beans.factory.BeanFactory;
import xyz.zcq.springframework.beans.factory.config.BeanDefinition;

/**
 * 抽象 bean 工厂
 */
public abstract class AbstractBeanFactory extends DefaultSingletonBeanRegistry implements BeanFactory {

    @Override
    public Object getBean(String name) throws BeanException {
        return doGetBean(name, null);
    }

    @Override
    public Object getBean(String name, Object... args) throws BeanException {
        return doGetBean(name, args);
    }

    protected Object doGetBean(String name, final Object... args) {
        Object bean = super.getSingleton(name);
        if (bean != null) {
            return bean;
        }

        return createBean(name, getBeanDefinition(name), args);
    }

    /**
     * 创建 bean 实例
     *
     * @param beanName       bean 名称
     * @param beanDefinition bean 定义
     * @return bean 实例
     */
    protected abstract Object createBean(String beanName, BeanDefinition beanDefinition, Object[] args);

    /**
     * 获取 bean 定义
     *
     * @param beanName bean 名称
     * @return bean 定义
     */
    protected abstract BeanDefinition getBeanDefinition(String beanName);

}
